﻿using System;
using System.Collections.Generic;

using HL.Lib.MVC;
using HL.Lib.Models;
using HL.Lib.Global;

namespace HL.Lib.CPControllers
{
    public class ModPropertyController : CPController
    {
        public ModPropertyController()
        {
            //khoi tao Service
            DataService = ModPropertyService.Instance;
            CheckPermissions = true;
        }

        public void ActionIndex(ModPropertyModel model)
        {
            // sap xep tu dong
            string orderBy = AutoSort(model.Sort);

            // tao danh sach
            var dbQuery = ModPropertyService.Instance.CreateQuery()
                                .Where(!string.IsNullOrEmpty(model.SearchText), o => o.Name.Contains(model.SearchText))
                                .Where(o=>o.ParentID==model.ParentID)
                                .Take(model.PageSize)
                                .OrderBy(orderBy)
                                .Skip(model.PageIndex * model.PageSize);

            ViewBag.Data = dbQuery.ToList();
            model.TotalRecord = dbQuery.TotalRecord;
            ViewBag.Model = model;
        }

        public void ActionAdd(ModPropertyModel model)
        {
            if (model.RecordID > 0)
            {
                entity = ModPropertyService.Instance.GetByID(model.RecordID);

                // khoi tao gia tri mac dinh khi update
            }
            else
            {
                entity = new ModPropertyEntity();

                // khoi tao gia tri mac dinh khi insert
                entity.Order = GetMaxOrder();
            }

            ViewBag.Data = entity;
            ViewBag.Model = model;
        }

        public void ActionSave(ModPropertyModel model)
        {
            if (ValidSave(model))
               SaveRedirect();
        }

        public void ActionApply(ModPropertyModel model)
        {
            if (ValidSave(model))
               ApplyRedirect(model.RecordID, entity.ID);
        }

        public void ActionSaveNew(ModPropertyModel model)
        {
            if (ValidSave(model))
               SaveNewRedirect(model.RecordID, entity.ID);
        }

        //public void ActionSearch(int[] arrID)
        //{
        //    string sid = HL.Core.Global.Array.ToString(arrID);
        //    DataService.Update("[ID] IN (" + sid + ")",
        //            "@Search", 1);

        //    //thong bao
        //    CPViewPage.SetMessage("Đã thêm tiêu chí tìm kiếm thành công.");
        //    CPViewPage.RefreshPage();
        //}

        //public void ActionUnSearch(int[] arrID)
        //{
        //    string sid = HL.Core.Global.Array.ToString(arrID);
        //    DataService.Update("[ID] IN (" + sid + ")",
        //            "@Search", 0);

        //    //thong bao
        //    CPViewPage.SetMessage("Đã bỏ tiêu chí tìm kiếm thành công.");
        //    CPViewPage.RefreshPage();
        //}

        public override void ActionDelete(int[] arrID)
        {
            List<int> list;
            bool success = true;
            string notValid = string.Empty;

            List<ModNewsPropertyEntity> listFood;
            for (int j = 0; arrID != null && j < arrID.Length; j++)
            {
                int parentid = (int)arrID[j];
                var parent = ModPropertyService.Instance.GetByID(parentid);
                list = new List<int>();
                bool tc = true;
                if (parent != null)
                {
                    //xoa cac thuoc tinh con
                    GetPropertyIDChild2(ref list, parent.ID);
                    for (int i = 0; list != null && i < list.Count; i++)
                    {
                        int menuid = list[i];
                        listFood = ModNewsPropertyService.Instance.CreateQuery()
                            .Where(o => o.PropertyID == menuid || o.PropertyValueID == menuid)
                            .ToList();
                        if (listFood != null && listFood.Count > 0)
                        {
                            var menu = ModPropertyService.Instance.GetByID(menuid);
                            tc = false;//neu co bat ki thuoc tinh con nao khong xoa duoc thi thuoc tinh cha cung khong xoa duoc
                            notValid += (string.IsNullOrEmpty(notValid) ? "" : ",") + menu.Name;
                        }
                        else
                        {
                            ModPropertyService.Instance.Delete(menuid);
                        }
                    }
                    //xoa thuoc tinh cha
                    if (tc)
                    {
                        var food = ModNewsPropertyService.Instance.CreateQuery()
                            .Where(o => o.PropertyID == parentid || o.PropertyValueID == parentid)
                            .ToSingle();
                        if (food == null)
                        {
                            ModPropertyService.Instance.Delete(o => o.ID == parentid);
                        }
                        else
                        {
                            notValid += (string.IsNullOrEmpty(notValid) ? "" : ",") + parent.Name;
                            success = false;
                        }
                    }
                    else
                    {
                        notValid += (string.IsNullOrEmpty(notValid) ? "" : ",") + parent.Name;
                        success = false;
                    }
                }
            }

            //thong bao
            if (success)
                CPViewPage.SetMessage("Đã xóa thành công.");
            else CPViewPage.SetMessage("Không thể xóa các thuộc tính '" + notValid + "' vì có các sản phẩm có các thuộc tính này.");
            CPViewPage.RefreshPage();
        }

        // lấy id thuộc tính cấp con
        private void GetPropertyIDChild(ref List<int> list, int menu_id)
        {
            list.Add(menu_id);

            List<ModPropertyEntity> _ListMenu = ModPropertyService.Instance.CreateQuery()
                                                .Where(o => o.ParentID == menu_id)
                                                .ToList();

            for (int i = 0; _ListMenu != null && i < _ListMenu.Count; i++)
            {
                GetPropertyIDChild(ref list, _ListMenu[i].ID);
            }
        }
        private void GetPropertyIDChild2(ref List<int> list, int menu_id)
        {
            //list.Add(menu_id);

            List<ModPropertyEntity> _ListMenu = ModPropertyService.Instance.CreateQuery()
                                                .Where(o => o.ParentID == menu_id)
                                                .ToList();

            for (int i = 0; _ListMenu != null && i < _ListMenu.Count; i++)
            {
                GetPropertyIDChild(ref list, _ListMenu[i].ID);
            }
        }
        //

        #region private func

        private ModPropertyEntity entity = null;

        private bool ValidSave(ModPropertyModel model)
        {
            TryUpdateModel(entity);

            //chong hack
            entity.ID = model.RecordID;

            ViewBag.Data = entity;
            ViewBag.Model = model;

            CPViewPage.Message.MessageType = Message.MessageTypeEnum.Error;

            //thêm nhiều
            if (!string.IsNullOrEmpty(model.Arrange))
            {
                string[] array = model.Arrange.Split('\n');
                if (array.Length > 0)
                {
                    try
                    {
                        for (int i = 0; i < array.Length; i++)
                        {
                            string s = array[i].Trim();
                            if (string.IsNullOrEmpty(s)) continue;
                            if (s.StartsWith("\\")) continue;
                            //nếu trùng 1 menu đã có trong DB
                            //var ob = ModPropertyService.Instance.CreateQuery()
                            //    .Where(o => o.Name == s)
                            //    .ToSingle();
                            //if (ob != null) s += " Bản sao";
                            //
                            var parent = ModPropertyService.Instance.GetByID(model.ParentID);
                            if (parent == null) throw new Exception("Danh mục cha không được là danh mục root !");
                            ModPropertyService.Instance.Save(new ModPropertyEntity()
                            {
                                ParentID = model.ParentID,
                                Name = s,
                                Order = GetMaxOrder()
                            });
                        }
                        return true;
                    }
                    catch (Exception ex)
                    {
                        HL.Lib.Global.Error.Write(ex);
                        CPViewPage.SetMessage("Lỗi : " + ex.Message);
                    }
                }
            }

            //kiem tra quyen han
            if ((model.RecordID < 1 && !CPViewPage.UserPermissions.Add) || (model.RecordID > 0 && !CPViewPage.UserPermissions.Edit))
                CPViewPage.Message.ListMessage.Add("Quyền hạn chế.");

            //kiem tra ten 
            if (entity.Name.Trim() == string.Empty)
                CPViewPage.Message.ListMessage.Add("Nhập tên.");

            if (CPViewPage.Message.ListMessage.Count == 0)
            {

                try
                {
                    //save
                    ModPropertyService.Instance.Save(entity);
                }
                catch (Exception ex)
                {
                    Global.Error.Write(ex);
                    CPViewPage.Message.ListMessage.Add(ex.Message);
                    return false;
                }

                return true;
            }

            return false;
        }

        private int GetMaxOrder()
        {
            return ModPropertyService.Instance.CreateQuery()
                    .Max(o => o.Order)
                    .ToValue().ToInt(0) + 1;
        }

        #endregion
    }

    public class ModPropertyModel : DefaultModel
    {
        public string SearchText { get; set; }
        public int ParentID { get; set; }
        public string Arrange { get; set; }
    }
}

